'use client'

import { useSearchParams, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { ArrowLeft, Settings } from 'lucide-react'
import { ParameterEditorWithPermissions } from '@/components/parameter-editor-with-permissions'
import { useAuth } from '@/hooks/use-auth'
import { Suspense } from 'react'

function CommunicationParametersV2Content() {
  const searchParams = useSearchParams()
  const router = useRouter()
  
  const code = searchParams.get('code')
  const name = searchParams.get('name')
  const type = searchParams.get('type')
  const deviceId = searchParams.get('deviceId')
  const deviceName = searchParams.get('deviceName')

  const { user, loading: authLoading } = useAuth()

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    router.push('/login')
    return null
  }

  if (!code || !name || !type || !deviceId || !deviceName) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-red-600">参数错误</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600 mb-4">缺少必要的参数信息</p>
            <Button onClick={() => router.back()} className="w-full">
              返回上一页
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const getTableName = (type: string, code: string) => {
    // 根据code生成正确的表名格式
    if (code) {
      // 将 C2 转换为 table_c2 格式
      const tableCode = code.toLowerCase().replace(/[^a-z0-9]/g, '');
      return `table_${tableCode}`;
    }

    // 后备方案：使用类型映射
    const typeMap: Record<string, string> = {
      'naming': 'table_c2',  // 默认命名表
      'position': 'table_c4', // 默认位置表
      'basic': 'table_c18',   // 默认基础参数表
      'base_params': 'table_c18',
      'base': 'table_c18'
    }
    return typeMap[type] || 'table_c18'
  }

  const getTypeDisplayName = (type: string) => {
    const typeMap: Record<string, string> = {
      'naming': '命名参数',
      'position': '位置参数',
      'basic': '基础参数',
      'base_params': '基础参数'
    }
    return typeMap[type] || '参数'
  }

  const tableName = getTableName(type, code)
  const typeDisplayName = getTypeDisplayName(type)

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 页面头部 */}
        <div className="mb-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="outline"
                onClick={() => router.back()}
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="h-4 w-4" />
                <span>返回</span>
              </Button>
              
              <div>
                <h1 className="text-2xl font-bold text-gray-900">
                  {typeDisplayName} - {name}
                </h1>
                <div className="flex items-center space-x-2 mt-1">
                  <Badge variant="outline">{code}</Badge>
                  <Badge variant="secondary">{deviceName}</Badge>
                  <span className="text-sm text-gray-500">设备ID: {deviceId}</span>
                </div>
              </div>
            </div>

            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                onClick={() => router.push('/test-permissions')}
              >
                <Settings className="h-4 w-4 mr-2" />
                权限测试
              </Button>
            </div>
          </div>
        </div>

        {/* 参数编辑器 */}
        <ParameterEditorWithPermissions
          tableName={tableName}
          deviceId={parseInt(deviceId)}
          deviceName={deviceName}
          onSave={() => {
            // 可以在这里添加保存后的回调逻辑
            console.log('参数保存成功')
          }}
        />

        {/* 帮助信息 */}
        <Card className="mt-6">
          <CardHeader>
            <CardTitle className="text-lg">使用说明</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
              <div>
                <h4 className="font-medium text-gray-900 mb-2">权限说明</h4>
                <ul className="space-y-1">
                  <li>• 只能编辑您角色权限范围内的字段</li>
                  <li>• 不同数据来源需要对应的权限</li>
                  <li>• 管理员可以编辑所有字段</li>
                  <li>• 查看角色只能查看，不能编辑</li>
                </ul>
              </div>
              <div>
                <h4 className="font-medium text-gray-900 mb-2">操作提示</h4>
                <ul className="space-y-1">
                  <li>• 使用标签页切换不同数据来源</li>
                  <li>• 点击"显示所有字段"查看只读字段</li>
                  <li>• 必填字段标有红色星号(*)</li>
                  <li>• 保存前请确认所有必填字段已填写</li>
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

export default function CommunicationParametersV2Page() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    }>
      <CommunicationParametersV2Content />
    </Suspense>
  )
}
